<?php
declare (strict_types = 1);

namespace app\middleware;

use app\BaseController;
use app\exception\AuthException;
use app\utils\jwt;
use think\facade\Cache;
use think\Response;

class AdminAuth extends BaseController
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $token = $this->request->header('Authorization');
        // 判断token是否为空 为空则抛出异常
        if ($token == null) throw new AuthException('未登录!');
        // 调用jwt类使用admin为key
        $jwt = new jwt('admin');
        try {
            // 对token进行解码
            $result = $jwt->checkoutToken($token)['data'];
            // 获取数组中的user_id
            $user_id = $result['user_id'];
        }catch (\Exception $exception){
            throw new AuthException($exception->getMessage());
        }

        // 判断redis中缓存的token是否和当前上传的token一致 实现单设备登录
        if (Cache::store('redis')->get("user:$user_id-role:admin:token") != $token) throw new AuthException('登录状态已过期!');
        // 设置给下一跳请求的user_id
        $this->request->user_id = $user_id;
        // 下一跳
        return $next($result);
    }
}
